package com.chipcoo.shiro.filters;

import com.chipcoo.captcha.geetest.GeetestLib;
import com.chipcoo.utils.BeanUtils;
import com.chipcoo.utils.ValidateUtils;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.PathMatcher;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import static com.chipcoo.web.utils.WebUtils.isHttpPost;

public class ValidateFilter extends PathMatchingFilter {
    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest req = WebUtils.toHttp(request);

        //是否需要启用验证码，一直让Filter继续下去
        if(ValidateUtils.isCaptchaEnabled(req)) {


            if( isHttpPost(req)){
                ValidateUtils.validateRequest(request);

            }
           /* else{
                //region 生产 geetest challenge,用于前端生产geetest
                ValidateUtils.createCaptcha(false);
               *//* if( geetestLib.preProcess() == 1) {
                    JSONObject jo = JSON.parseObject(geetestLib.getResponseStr());
                    String challenge = jo.getString("challenge");
                    request.setAttribute(GeetestLib.fn_geetest_challenge,challenge);
                }*//*
                //endregion
            }*/
        }

        return  true;
    }
    @Override
    protected boolean pathsMatch(String pattern, String path) {
        return BeanUtils.getBean("pathMatching", PathMatcher.class).match(pattern,path);
    }

}
